<template>
  <div class="product-detail">
    <div class="container">
      <div v-loading="loading">
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/" class="breadcrumb">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/products' }">商品列表</el-breadcrumb-item>
          <el-breadcrumb-item>{{ product.name || '商品详情' }}</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 商品详情内容 -->
        <div v-if="product.id" class="product-content">
          <el-row :gutter="40">
            <!-- 商品图片 -->
            <el-col :span="12">
              <div class="product-image-container">
                <img
                  :src="product.image || '/placeholder.jpg'"
                  :alt="product.name"
                  class="product-image"
                  @error="handleImageError"
                />
              </div>
            </el-col>

            <!-- 商品信息 -->
            <el-col :span="12">
              <div class="product-info">
                <h1 class="product-name">{{ product.name }}</h1>
                <div class="product-price">
                  <span class="price">¥{{ product.price }}</span>
                </div>
                
                <div class="product-stock">
                  <el-tag :type="product.stock > 0 ? 'success' : 'danger'">
                    {{ product.stock > 0 ? `库存: ${product.stock}` : '缺货' }}
                  </el-tag>
                </div>

                <div class="product-description">
                  <h3>商品描述</h3>
                  <p>{{ product.description || '暂无描述' }}</p>
                </div>

                <!-- 购买操作 -->
                <div class="product-actions">
                  <div class="quantity-selector">
                    <span class="label">数量:</span>
                    <el-input-number
                      v-model="quantity"
                      :min="1"
                      :max="product.stock"
                      :disabled="product.stock <= 0"
                      size="large"
                    />
                  </div>
                  
                  <div class="action-buttons">
                    <el-button
                      type="primary"
                      size="large"
                      @click="addToCart"
                      :disabled="product.stock <= 0"
                      :loading="addingToCart"
                    >
                      <el-icon><ShoppingCart /></el-icon>
                      加入购物车
                    </el-button>
                    
                    <el-button
                      type="danger"
                      size="large"
                      @click="buyNow"
                      :disabled="product.stock <= 0"
                    >
                      立即购买
                    </el-button>
                    <el-button
                      type="danger"
                      size="large"
                      @click="seckill"
                      :disabled="product.stock <= 0"
                    >
                      立即秒杀
                    </el-button>
                  </div>
                </div>

                <!-- 商品属性 -->
                <div class="product-attributes">
                  <el-descriptions :column="1" border>
                    <el-descriptions-item label="商品ID">{{ product.id }}</el-descriptions-item>
                    <el-descriptions-item label="分类ID">{{ product.categoryId }}</el-descriptions-item>
                    <el-descriptions-item label="状态">
                      <el-tag :type="product.status === 1 ? 'success' : 'info'">
                        {{ product.status === 1 ? '上架' : '下架' }}
                      </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="创建时间">
                      {{ formatDate(product.createTime) }}
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 加载失败 -->
        <el-empty
          v-else-if="!loading"
          description="商品不存在或已下架"
        >
          <el-button type="primary" @click="$router.push('/products')">
            返回商品列表
          </el-button>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ShoppingCart } from '@element-plus/icons-vue'
import { getProductById } from '@/api/product'
import { useCartStore } from '@/stores/cart'
import { useUserStore } from '@/stores/user'
import { seckillOrder } from '@/api/seckill'

const route = useRoute()
const router = useRouter()
const cartStore = useCartStore()
const userStore = useUserStore()

// 响应式数据
const product = ref({})
const loading = ref(false)
const addingToCart = ref(false)
const quantity = ref(1)

// 计算属性
const isLoggedIn = computed(() => userStore.isLoggedIn)

// 方法
const fetchProductDetail = async () => {
  const productId = route.params.id
  if (!productId) {
    ElMessage.error('商品ID不存在')
    router.push('/products')
    return
  }

  try {
    loading.value = true
    const response = await getProductById(productId)
    if (response.data) {
      product.value = response.data
    } else {
      ElMessage.error('商品不存在')
      router.push('/products')
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
    router.push('/products')
  } finally {
    loading.value = false
  }
}

const addToCart = async () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  if (quantity.value > product.value.stock) {
    ElMessage.warning('购买数量不能超过库存')
    return
  }

  try {
    addingToCart.value = true
    const success = await cartStore.addItemToCart(product.value.id, quantity.value)
    if (success) {
      ElMessage.success('已添加到购物车')
      quantity.value = 1
    }
  } catch (error) {
    console.error('添加购物车失败:', error)
  } finally {
    addingToCart.value = false
  }
}

const buyNow = async () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  if (quantity.value > product.value.stock) {
    ElMessage.warning('购买数量不能超过库存')
    return
  }

  try {
    // 先添加到购物车
    const success = await cartStore.addItemToCart(product.value.id, quantity.value)
    if (success) {
      // 跳转到购物车页面
      router.push('/cart')
    }
  } catch (error) {
    console.error('购买失败:', error)
  }
}

const seckill = async () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  try {
    const response = await seckillOrder(product.value.id)
    if (response.code === 200) {
      ElMessage.success('秒杀成功！请到订单中心查看')
      // 可选：跳转到订单tab
      // router.push('/user?tab=seckill')
    } else {
      ElMessage.error(response.message || '秒杀失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '秒杀失败')
  }
}

const handleImageError = (event) => {
  event.target.src = '/placeholder.jpg'
}

const formatDate = (dateString) => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  fetchProductDetail()
})
</script>

<style scoped>
.product-detail {
  padding: 20px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.breadcrumb {
  margin-bottom: 30px;
}

.product-content {
  margin-top: 20px;
}

.product-image-container {
  text-align: center;
  margin-bottom: 20px;
}

.product-image {
  max-width: 100%;
  max-height: 500px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.product-info {
  padding: 20px;
}

.product-name {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0 0 20px 0;
  line-height: 1.4;
}

.product-price {
  margin-bottom: 20px;
}

.price {
  font-size: 28px;
  font-weight: bold;
  color: #e74c3c;
}

.product-stock {
  margin-bottom: 20px;
}

.product-description {
  margin-bottom: 30px;
}

.product-description h3 {
  font-size: 16px;
  color: #333;
  margin-bottom: 10px;
}

.product-description p {
  color: #666;
  line-height: 1.6;
  margin: 0;
}

.product-actions {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.quantity-selector {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.quantity-selector .label {
  margin-right: 10px;
  font-weight: bold;
  color: #333;
}

.action-buttons {
  display: flex;
  gap: 15px;
}

.product-attributes {
  margin-top: 30px;
}

@media (max-width: 768px) {
  .product-content .el-row {
    flex-direction: column;
  }
  
  .product-content .el-col {
    width: 100% !important;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
}
</style> 